//使用nodejs实现非对称加密RSA
//1.生成公钥和私钥
const crypto = require('crypto');

const {publicKey, privateKey} = crypto.generateKeyPairSync('rsa', {
	modulusLength: 2048,
	publicKeyEncoding: {
		type: 'pkcs1',
		format: 'pem'
	},
	privateKeyEncoding: {
		type: 'pkcs1',
		format: 'pem'
	},
})
console.log("公钥：", publicKey)
console.log("私钥：", privateKey)

//2.使用公钥加密 使用私钥解密
const encrypted = crypto.publicEncrypt(publicKey, Buffer.from('hello world'))
console.log(encrypted.toString('base64'))
const decrypted = crypto.privateDecrypt(privateKey, encrypted)
console.log(decrypted.toString('utf8'))

//3.使用私钥加密 使用公钥解密
const encrypted2 = crypto.privateEncrypt(privateKey, Buffer.from('hello world'))
console.log(encrypted2.toString('base64'))
const decrypted2 = crypto.publicDecrypt(publicKey, encrypted2)
console.log(decrypted2.toString('utf8'))
